/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import app from '@system.app';
import prompt from '@system.prompt';
import storage from '@system.storage';
import dataParser from '../../../share/common/dataParser';
import hekOperator from '@health-ecology-kit/hek-operator';
import centralOperator from '../../../share/common/scripts/centralOperator';
import HuaweiAccount from '../../../../js/share/common/scripts/HuaweiAccount';
import TitleBarParams from '../../../share/common/components/titleBar/TitleBarParams';
import SliderBarParams from '../../../share/common/components/sliderBar/SliderBarParams';
import MenuButtonParams from '../../../share/common/components/menuButton/MenuButtonParams';
import DialogBoxParams from '../../../share/common/components/dialog/dialogBox/DialogBoxParams';
import ToggleSwitchParam from '../../../share/common/components/toggleSwitch/ToggleSwitchParams';
import ToggleButtonParams from '../../../share/common/components/toggleButton/ToggleButtonParams';
import AdjusterButtonParams from '../../../share/common/components/adjusterButton/AdjusterButtonParams';
import DeviceStateConstants from '../../../share/common/components/deviceStatusCard/DeviceStateConstants'
import CountdownButtonParams from '../../../share/common/components/countdownButton/CountdownButtonParams';
import ModesSwitchPanelParams from '../../../share/common/components/modesSwitchPanel/ModesSwitchPanelParams';
import InformationPanelParams from '../../../share/common/components/informationPanel/InformationPanelParams';
import DeviceStatusCardDoubleIconParams from '../../../share/common/components/deviceStatusCard/doubleIcon/DeviceStatusCardDoubleIconParams';
import DeviceStatusCardProgressParams from '../../../share/common/components/deviceStatusCard/progress/DeviceStatusCardProgressParams';
import DeviceStatusCardSingleIconParams from '../../../share/common/components/deviceStatusCard/singleIcon/DeviceStatusCardSingleIconParams';
import DeviceStatusCardTextParams from '../../../share/common/components/deviceStatusCard/text/DeviceStatusCardTextParams';
import DeviceStatusCardIconTextParams from '../../../share/common/components/deviceStatusCard/iconText/DeviceStatusCardIconTextParams';
import router from '@system.router';
const JS_TAG = 'JS/Page/Dashboard/index: ';
const AUDIO_ON = 'audio_on';
const AUDIO_OFF = 'audio_off';
const TOKEN_INVALID_ERROR_CODE = 1203;
const ENABLE_NOTIFY = true;
const SERVICE_UUID = '0000fff0-0000-1000-8000-00805f9b34fb';
const CHARACTER_UUID = '0000fff1-0000-1000-8000-00805f9b34fb';
const WRITE_UUID = '0000fff2-0000-1000-8000-00805f9b34fb';

export default {
    data: {
        isFullScreen: false,
        macAddress: undefined,
        productLogoIcon: '/common/img/base/ic_public_hw_logo.png',
        //组件数据初始化，必选
        deviceStatus: 0,
        deviceStatusType: DeviceStateConstants.PROGRESS,
        titlesBarConfig: undefined,
        DeviceStatusCardProgressData: undefined,
        DeviceStatusCardTextData: undefined,
        countdownButtonData: undefined,
        isConnected: false,
        status: "1",
        dl: "0",
    },
    ////////////////////////////////////////
    ////////       生命周期事件      ////////
    onInit() {
        console.debug(JS_TAG + 'onInit.');
        try {
            this.checkAccessToken();
        } catch (e) {
            console.error(JS_TAG + 'checkAccessToken error = ' + e);
        }
        this.initParams();
        this.initComponents();
        this.initBleListeners();
    },
    onShow() {
        console.info(JS_TAG + 'onShow');
    },
    onDestroy() {
        console.info(JS_TAG + 'onDestroy, macAddress = ' + this.macAddress);
        app.terminate();
        this.disconnectToDevice(this.macAddress);
    },
    onHide() {
        console.info(JS_TAG + 'onHide.');
    },
    onBackPress() {
        console.info(JS_TAG + 'onBackPress.');
        this.exit();
    },
    ////////////////////////////////////////
    ///////     页面初始化      ////////
    initParams() {
        this.$app.$def.globalData.isDarkMode = this.isDarkMode;
        console.debug(JS_TAG + 'initParams isDarkMode = ' + this.isDarkMode);
        if (this.params == undefined) {
            console.error(JS_TAG + 'initParams params undefined');
        } else {
            let paramJson = JSON.parse(this.params);
            console.debug(JS_TAG + 'initParams paramJson = ' + JSON.stringify(paramJson));
            this.macAddress = paramJson.macAddress;
            this.productId = paramJson.productId;
            this.$app.$def.globalData.productId = this.productId;
            this.$app.$def.globalData.macAddress = paramJson.macAddress;
        }
    },
    ////////////////////////////////////////
    ///////      登录状态监测       ////////
    checkAccessToken() {
        HuaweiAccount.refreshAccessToken((data, code) => {
            let date = new Date();
            date.setHours(date.getHours() + 1);
            this.$app.$def.globalData.accessToken = data.access_token;
            this.$app.$def.globalData.accessTokenExpireTimestamp = date.getTime();
        }, this.processCheckAccessTokenFailed)
    },
    processCheckAccessTokenFailed(data, code) {
        console.error(JSON.stringify(data))
        if (data.error == TOKEN_INVALID_ERROR_CODE) {
            this.onLoggedOut();
        }
    },
    onLoggedOut() {
        storage.set({
            key: 'rt_expire_timestamp',
            value: '0'
        })
        storage.delete({
            key: 'refresh_token'
        })
        prompt.showDialog({
            title: this.$t('strings.public_logged_out'),
            message: this.$t('strings.public_logged_out_message'),
            buttons: [
                {
                    text: this.$t('strings.public_got_it'),
                    color: '#0A59F7',
                },
                {
                    text: this.$t('strings.public_log_in'),
                    color: '#0A59F7',
                },
            ],
            success: (data) => {
                if (data.index == 1) {
                    app.requestFullWindow();
                    this.isFullScreen = true;
                    this.$app.$def.globalData.isFullScreen = true;
                    HuaweiAccount.signIn();
                }
            },
            cancel: () => {
                console.log('dialog cancel callback');
            },
        })
    },
    ////////////////////////////////////////
    ///////     注册蓝牙事件      ///////////
    initBleListeners() {
        console.debug(JS_TAG + 'initBleListeners');
        hekOperator.onBleServiceDiscovered(this.bleServiceDiscoveredCallback);
        hekOperator.onBleConnectionStateChange(this.bleConnectionStateCallback);
        hekOperator.onBluetoothAdapterStateChange(this.bluetoothAdapterStateCallback);
        hekOperator.onBleCharacteristicValueChange(this.bleCharacteristicChangeCallback);
        this.enableNotifyAndIndicate();
    },
    initComponents() {
        this.initTitleBar();
        this.initCountdownButton();
        this.initDeviceStatusCardProgress();
        this.initDeviceStatusCardText();
    },
    ////////////////////////////////////////
    ////////      控件初始化示例     /////////
    initTitleBar() {
        let deviceResource = this.$t('resources.' + this.productId);
        this.titlesBarConfig = TitleBarParams.getTitleBarConfig(
            {
                title: deviceResource.device_name,
                menuOptions: this.$t('resources.' + this.productId).menu_options
            });
    },
    initCountdownButton() {
        this.countdownButtonConfig = CountdownButtonParams.getCountdownButtonConfig({
            title: this.$t('strings.modeString'),
            indicatorSuffix: '',
            range: [this.$t('strings.mode1'), this.$t('strings.mode2'), this.$t('strings.mode3')],
        });
        this.countdownButtonData = CountdownButtonParams.getCountdownButtonData({
            defaultValue: this.$t('strings.mode1'),
            defaultSubTitle: this.$t('strings.mode1')
        });
    },
    initDeviceStatusCardProgress() {
        this.DeviceStatusCardProgressData = DeviceStatusCardProgressParams.getDeviceStatusCardProgressData({
            title: this.$t('strings.connecting'),
        });
    },
    initDeviceStatusCardText() {
        this.DeviceStatusCardTextData = DeviceStatusCardTextParams.getDeviceStatusCardTextData({
            title: this.$t('strings.NotConnected'),
            middleTitle: '',
            subTitle: '',
            rightText: this.$t('strings.reconnect'),
        });
    },
    ////////////////////////////////////////
    ////////     控件事件处理示例    /////////
    //
    onCountDownStateChange(changeEvent) {
        console.debug(JS_TAG + 'onCountDownStateChange changeValue = ' + changeEvent.detail.value);
        this.countdownButtonData = CountdownButtonParams.getCountdownButtonData({
            defaultValue: changeEvent.detail.value,
            defaultSubTitle: changeEvent.detail.value
        })
        var inster = '55aa06';
        if (changeEvent.detail.value == this.$t('strings.mode1')) {
            inster += '820183';
        }
        else if (changeEvent.detail.value == this.$t('strings.mode2')) {
            inster += '820284';
        }
        else {
            inster += '820385';
        }
        this.bleWriteBleCharacteristicValue(inster);
    },
    //
    onClickText() {
        this.deviceStatus = 1;
        this.updateDeviceStatusType(DeviceStateConstants.PROGRESS);
    },
    updateDeviceStatusType(newDeviceStatusType) {
        // 使用此函数以在状态之间进行转换，对应状态将显示对应的页面。
        console.debug('Trying changing deviceStatusCardType to: ' + newDeviceStatusType);
        this.deviceStatusType = newDeviceStatusType;
        if (newDeviceStatusType == DeviceStateConstants.PROGRESS) {
            this.connectToDevice(this.macAddress);
        }
        if (this.isConnected) {
            var that = this;
            setTimeout(function () {
                console.debug('延迟操作')
                hekOperator.writeBleCharacteristicValue({
                    deviceId: that.macAddress,
                    serviceId: SERVICE_UUID,
                    characteristicId: WRITE_UUID,
                    characteristicData: '55aa06020002',
                    success: () => {
                        console.debug(JS_TAG + 'write success');
                    },
                    fail: (result) => {
                        console.debug(JS_TAG + 'write error:' + result);
                    }
                });

            }, 1000);
        }
    },
    //
    requestFullWindow() {
        this.$app.$def.globalData.isFullScreen = true;
        this.isFullScreen = true;
        app.requestFullWindow();
    },
    exit() {
        console.info(JS_TAG + 'exit.');
        app.terminate();
    },
    ////////////////////////////////////////
    ////////       蓝牙接口调用       ////////
    reConnect() {
        console.debug(JS_TAG + 'Reconnect!')
        hekOperator.getBluetoothAdapterState({
            success: this.onCheckAdapterState,
            fail: this.onCheckAdapterStateFailed
        });
    },
    connectToDevice(deviceId) {
        hekOperator.createBleConnection({
            deviceId: deviceId,
            isAutoConnect: false,
            success: () => {
                console.debug(JS_TAG + 'Create ble connection success!');
            },
            fail: this.onDevcieConnectFailed
        })
    },
    disconnectToDevice(deviceId) {
        hekOperator.closeBleConnection({
            deviceId: deviceId,
            success: () => {
                console.debug(JS_TAG + 'Close ble connection success!');
            },
            fail: (code, err) => {
                console.error(JS_TAG + 'Close ble connection error, code is ' + code + ', message is ' + JSON.stringify(err));
            }
        })
    },
    async enableNotifyAndIndicate() {
        hekOperator.notifyBleCharacteristicValueChange({
            deviceId: this.macAddress,
            serviceId: SERVICE_UUID,
            characteristicId: CHARACTER_UUID,
            enableNotify: ENABLE_NOTIFY,
            success: () => {
                console.debug(JS_TAG + 'Enable notify and indicate success!');
                this.isConnected = true;
                this.updateDeviceStatusType(DeviceStateConstants.TEXT);
                this.DeviceStatusCardTextData = DeviceStatusCardTextParams.getDeviceStatusCardTextData({
                    title: this.$t('strings.connected'),
                    middleTitle: '',
                    subTitle: '',
                    rightText: "",
                });
            },
            fail: this.onEnableNotifyFailed
        });
    },
    ////////////////////////////////////////
    ////////        蓝牙回调处理       ///////
    bluetoothAdapterStateCallback(adapterState) {
            adapterState.isAvailable ? this.onAdapterAvailable() : this.onAdapterNotAvailable();
    },
    bleConnectionStateCallback(connectionState) {
        console.debug(JS_TAG + 'Connection state changed: ' + JSON.stringify(connectionState));
        if (connectionState.isConnected) {
            this.exceptionHintLabel = 'Device connected.';
        } else {
            this.exceptionHintLabel = 'Device disconnected.';
            this.isConnected = false;
            this.status = '';
            this.dl = '';
            this.deviceStatus = 1;
            this.updateDeviceStatusType(DeviceStateConstants.TEXT);
            this.DeviceStatusCardTextData = DeviceStatusCardTextParams.getDeviceStatusCardTextData({
                title: this.$t('strings.NotConnected'),
                middleTitle: '',
                subTitle: '',
                rightText: this.$t('strings.reconnect'),
            });
        }
    },
    bleServiceDiscoveredCallback(bleServiceDiscoveredResult) {
        console.debug(JS_TAG + 'onBleServiceDiscovered = ' + JSON.stringify(bleServiceDiscoveredResult));
        if (bleServiceDiscoveredResult.isDiscoverySuccess) {
            this.enableNotifyAndIndicate();
        } else {
            console.error(JS_TAG + 'ble service discovered failed.');
            this.isConnected = false;
            this.status = '';
            this.dl = '';
        }
    },
    ///蓝牙上报
    bleCharacteristicChangeCallback(bleCharacteristicChangeValue) {
        //    let result = dataParser.dealWithCharacteristicValue(this.macAddress,
        //      bleCharacteristicChangeValue.data.characteristicId, bleCharacteristicChangeValue.data.changeData);
        let char = bleCharacteristicChangeValue.characteristicData;
        var type = char.slice(10, 12)
        var dls = char.slice(12, 14)
        if (this.status != type) {
            this.status = type
            var str = ""
            if (type == '01') {
                str = this.$t('strings.mode1')
            }
            else if (type == '02') {
                str = this.$t('strings.mode2')
            }
            else {
                str = this.$t('strings.mode3')
            }
            this.countdownButtonData = CountdownButtonParams.getCountdownButtonData({
                defaultValue: str,
                defaultSubTitle: str
            });
        }
        if (this.dl != dls) {
            this.dl = dls
            this.DeviceStatusCardTextData = DeviceStatusCardTextParams.getDeviceStatusCardTextData({
                title: this.$t('strings.connected'),
                middleTitle: parseInt(dls, 16) + '%',
                subTitle: this.$t('strings.dl'),
                rightText: "",
            });
        }
        console.debug(JS_TAG + 'onBleCharacteristicValueChange result = ' + char);
    },
    ///蓝牙写入操作
    bleWriteBleCharacteristicValue(value) {
        console.debug("mac地址是:" + this.macAddress + ",value:" + value);
        var instructionString = value;
        hekOperator.writeBleCharacteristicValue({
            deviceId: this.macAddress,
            serviceId: SERVICE_UUID,
            characteristicId: WRITE_UUID,
            characteristicData: instructionString,
            success: () => {
                console.debug(JS_TAG + 'write success');
            },
            fail: (result) => {
                console.debug(JS_TAG + 'write error:' + result);
            }
        });
    },
    ////////////////////////////////////////
    ////////        页面流程处理       ///////
    onDevcieConnectFailed(errorCode, errorMessage) {
    },
    onDeviceDiscoveryFailed(errorCode, errorMessage) {
    },
    onServiceDiscoveredFailed() {
    },
    onEnableNotifyFailed(errorCode, errorMessage) {
    },
    onAdapterOpenFailed(errorCode, errorMessage) {
    },
    onStopDeviceDiscoveryFailed(errorCode, errorMessage) {
    },
    onCheckAdapterStateFailed(errorCode, errorMessage) {
    },
    onStartDiscoverySuccess() {
    },
    onTargetDeviceFound(deviceId) {
    },
    onStartConnectSuccess() {
    },
    onServiceDiscoveredSuccess() {
    },
    onCheckAdapterStateSuccess(bluetoothAdapterState) {
            bluetoothAdapterState.isAvailable ? this.onAdapterAvailable() : this.onCheckAdapterNotAvailable();
    },
    onCheckAdapterNotAvailable() {
    },
    onAdapterAvailable() {
    },
    onAdapterNotAvailable() {
    },

    ////////////////////////////////////////
    ////////        conponenets回调函数集中处理       ///////
    FeaturedCard() {
        console.log("FeaturedCard")
        router.push({
            uri: 'pages/services/services',
        });
    },
    DialogBox() {
        console.log("DialogBox")
        router.push({
            uri: 'pages/services/services',
        });
    },
    DeviceStatusCardDoubleIcon() {
        console.log(" DeviceStatusCardDoubleIcon")
        router.push({
            uri: 'pages/services/services',
        });
    },
    DeviceDisplay() {
        console.log(" DeviceStatusCardDoubleIcon")
        router.push({
            uri: 'pages/services/services',
        });
    },
    CountdownButton() {
        console.log(" CountdownButton")
        router.push({
            uri: 'pages/services/services',
        });
    },
    CircularProgressBar() {
        console.log(" CircularProgressBar")
        router.push({
            uri: 'pages/services/services',
        });
    },
    AlertHint() {
        console.log(" AlertHint")
        router.push({
            uri: 'pages/services/services',
        });
    },
    AdjusterButton() {
        console.log("AdjusterButton")
        router.push({
            uri: 'pages/services/services',
        });
    }



}
